/**
 * @file 设备列表状态管理
 * @description 管理设备列表的状态和操作
 * @date 2024-03-09
 */

import { defineStore } from 'pinia'
// @ts-ignore
import { ref, computed } from 'vue'
import type { Device } from '@/types/device'
import type { ApiResponse } from '@/types'
import { getAllDevices } from '@/api/track'
import type { DeviceInfo, DeviceQueryParams, DeviceListResponse } from '@/types/track'
import { logger } from '@/utils/system/logger'

/**
 * 设备操作响应
 */
export interface DeviceResponse {
  success: boolean;
  message: string;
  data?: any;
}

/**
 * 设备管理Pinia Store
 */
export const useDeviceStore = defineStore('device', () => {
  // 状态
  const deviceList = ref<DeviceInfo[]>([]);
  const total = ref(0);
  const page = ref(1);
  const limit = ref(100);
  const loading = ref(false);
  const currentQuery = ref<DeviceQueryParams>({});
  const error = ref<string | null>(null);
  
  // 计算属性
  const onlineDevices = computed(() => 
    deviceList.value.filter((device: DeviceInfo) => device.status === 1)
  );

  /**
   * 获取设备列表
   */
  async function fetchDeviceList(params?: DeviceQueryParams) {
    try {
      loading.value = true;
      error.value = null;
      
      // 如果status为-1（全部），则从参数中删除status字段
      let queryParams = params ? { ...params } : {};
      if (queryParams.status === -1) {
        const { status, ...restParams } = queryParams;
        queryParams = restParams;
      }
      
      // 保存当前查询条件
      currentQuery.value = queryParams;
      
      const response = await getAllDevices(queryParams);
      
      if (response.success && response.data) {
        const { total: totalCount, page: currentPage, limit: pageLimit, devices } = response.data;

        // 确保设备列表是有效数组
        if (Array.isArray(devices)) {
          deviceList.value = devices;
          total.value = totalCount;
          page.value = currentPage;
          limit.value = pageLimit;
          logger.info('设备列表获取成功', { count: devices.length });
        } else {
          deviceList.value = [];
          error.value = '设备列表数据格式无效';
          logger.error('设备列表数据格式无效');
        }
      } else {
        error.value = response.message || '获取设备列表失败';
        logger.error('获取设备列表失败:', response.message);
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取设备列表出错';
      logger.error('获取设备列表异常:', err);
    } finally {
      loading.value = false;
    }
  }

  /**
   * 搜索设备
   */
  function searchDevices(keyword: string) {
    return fetchDeviceList({ ...currentQuery.value, keyword });
  }

  /**
   * 按状态筛选设备
   */
  function filterByStatus(status: number) {
    // 如果status为-1（全部），则不包含status字段
    if (status === -1) {
      const { keyword } = currentQuery.value;
      return fetchDeviceList(keyword ? { keyword } : undefined);
    }
    // 否则，包含status字段
    return fetchDeviceList({ ...currentQuery.value, status });
  }

  /**
   * 刷新设备列表
   */
  function refreshDeviceList() {
    return fetchDeviceList(currentQuery.value);
  }

  /**
   * 重置查询条件
   */
  function resetQuery() {
    currentQuery.value = {};
    return fetchDeviceList();
  }

  /**
   * 设置分页参数
   */
  function setPagination(pageNum: number, pageSize: number) {
    page.value = pageNum;
    limit.value = pageSize;
    return fetchDeviceList({
      ...currentQuery.value,
      page: pageNum,
      limit: pageSize
    });
  }

  // 在store初始化时自动加载设备列表
  function initialize() {
    fetchDeviceList();
  }
  
  // 自动初始化
  initialize();

  return {
    // 状态
    deviceList,
    total,
    page,
    limit,
    loading,
    currentQuery,
    error,
    
    // 计算属性
    onlineDevices,
    
    // 方法
    fetchDeviceList,
    searchDevices,
    filterByStatus,
    refreshDeviceList,
    resetQuery,
    setPagination
  };
}); 